<template>
  <div>
    <div class="tit">
      基本信息
    </div>
    <table>
      <tr>
        <th style="width: 15%;">
          所属标段
          <span class="red">*</span>
        </th>
        <td style="width: 25%;">
          <zz-select
            class="inline"
            style="width: 170px;padding: 0;"
            :border= false
            :options="{width: '100%'}"
            :option="periodList"
            :all = false
            optionColor = "#939997"
            :name = towerObject.stageName
            @optionClick="setPeriod">
          </zz-select>
        </td>
        <td style="width: 25%;">  
          <zz-select
            class="inline"
            style="width:170px;padding: 0;"
            :border= false
            :options="{width: '100%'}"
            :option="biaoduanList"
            :all = false
            optionColor = "#939997"
            :name = towerObject.sectionName
            @optionClick="setBiaoduan">
          </zz-select>
        </td>
        <th style="width: 15%;">
          自编号
          <span class="red">*</span>
        </th>
        <td style="width: 20%;">
          <zz-select
            class="inline mr10"
            style="width: 100%"
            :border= false
            :options="{width: '100%'}"
            :option="numList"
            :all = false
            optionColor = "#939997"
            :name = towerObject.code
            @optionClick="num">
          </zz-select>
        </td>
      </tr>
      <tr>
        <th>
          设备标识
          <span class="red">*</span>
        </th>
        <td colspan="2">
          <input v-model="towerObject.deviceName">
        </td>
        <th>
          绑定监控设备
        </th>
        <td>
          <p v-if="towerObject.referName || towerObject.deviceSn">{{towerObject.referName}} (SN: {{towerObject.deviceSn}})</p>
          <button class="chooseBtn pointer" @click="setReferId()" v-if="!towerItem || !towerItem.deviceId || !towerObject.referId">选择</button>
          <!-- <button class="chooseBtn pointer" @click="setReferId()">选择</button> -->
        </td>
      </tr>
      <tr>
        <th>自有设备</th>
        <td colspan="2">
          <zz-radio
            style="width: 100px"
            :key="item.id"
            :value = "item.id"
            v-for="item in radioList"
            @handle="handleRadio"
            :checked = item.check>
            {{item.name}}
          </zz-radio>
        </td>
        <th v-if="towerObject.isSelf">设备编码</th>
        <td v-if="towerObject.isSelf"><input v-model="towerObject.companyCode"></td>
      </tr>
    </table>
    <!-- 设备资料 -->
    <div class="tit">
      设备资料
    </div>
    <table>
      <tr>
        <th style="width: 15%;">
          生产厂家
        </th>
        <td style="width: 50%;">
          <input v-model="towerObject.producerName" class="producer-input">
          <zz-select
            class="inline"
            style="width: 400px"
            :border= false
            :options="{width: '100%'}"
            :option="producerList"
            :all = false
            optionColor = "#939997"
            :name = towerObject.producerName
            @optionClick="setProdecer">
          </zz-select>
        </td>
        <th style="width: 15%;">
          规格型号
        </th>
        <td style="width: 20%;">
          <input v-model="towerObject.modelName" class="modelName-input">
          <zz-select
            class="inline"
            style="width: 160px"
            :border= false
            :options="{width: '100%'}"
            :option="modelNameList"
            :all = false
            optionColor = "#939997"
            :name = towerObject.modelName
            @optionClick="setModel">
          </zz-select>
        </td>
      </tr>
      <tr>
        <th>
          出厂编号
        </th>
        <td>
          <input v-model="towerObject.outNumber">
        </td>
        <th>
          出厂日期
        </th>
        <td>
          <input v-model="towerObject.outDate" v-if="towerObject.outDate">
          <zz-date @change=handleChange type="day" inputClass='date-input-noborder'  v-if="!towerObject.outDate"></zz-date>
        </td>
      </tr>
      <tr>
        <th>初始登记号</th>
        <td>
          <input v-model="towerObject.initialNumber">
        </td>
        <th>最大安装高度(米)</th>
        <td>
          <input v-model="towerObject.maxHigh" type="number">
        </td>
      </tr>
      <tr>
        <th>使用年限</th>
        <td>
          <input v-model="towerObject.useYear" type="number">
        </td>
        <th>进场日期</th>
        <td>
          <input v-model="towerObject.enterTime" v-if="towerObject.enterTime">
          <zz-date @change=handleChange2 inputClass='date-input-noborder' type="day" v-if="!towerObject.enterTime"></zz-date>
        </td>
      </tr>
      <tr class="takePic">
         <th>设备安装性能表<br/>(拍照上传)</th>
        <td colspan="3">
          <div class="pic-contain">
            <zz-upload
              style="margin-left: 20px; margin-top: 20px; vertical-align: top;"
              width="50px"
              height="50px"
              button="plus"
              :propsFiles = "panoramaFile"
              :type="['png', 'jpg', 'jpeg']"
              updateTip=""
              :length = 9
              @updateFile="updatePanoramaFileHandel"
              :itype=3608>
            </zz-upload>
            <div>
              <!-- <zz-upload-list style="display: inline-block;width: 100%;"  :files="panoramaFileList"></zz-upload-list> -->
              <zz-upload-list style="display: inline-block;width: 100%;"  :files="picList"></zz-upload-list>
            </div>
          </div>
        </td>
      </tr>
    </table>
    <div class="footer-button">
      <button class="button-lr ml20 left" @click="goout" v-if="this.towerItem.status && this.towerItem.status !== 2 ">设备离场</button>
      <button class="button-line ml20 left" @click="regoin" v-if="this.towerItem.status && this.towerItem.status === 2 ">重新进场</button>
      <button class="button-lr ml10 left" @click="delTower" v-if="this.towerItem.status && this.towerItem.status === 2 ">删除设备</button>
      <button class="button-lb mr20 right" @click="save" v-if="this.towerItem.status !== 2">保存</button>
      <button class="button-lb mr10 right" @click="close" v-if="this.towerItem.status !== 2">取消</button>
    </div>

     <zz-dialog
      :title = dialogTitle
      :visible = showDialog
      :showConfirm = true
      :reset = true
      :showFoot = "true"
      @close="closeDialog"
      @confirm = confirm>
      <div class="dialog-box">
        <div style="width: 300px; height: 400px; overflow-y:scroll; overflow-x: hidden;">
          <div class="groupReferGroup" v-for="(item,index) in groupRefer" @click="chooseDevice(item,index)" :key="index">
            <div class="left-side">
              <i class="iconfont icon-zu4"></i>
            </div>
            <div class="right-side">
              <div>{{item.deviceName}}</div>
              <div>
                <span class="left">厂商: {{item.supply}}</span>
                <span class="right">SN: {{item.deviceSn}}</span>
              </div>
            </div>
            <i class="iconfont icon-success"></i>
          </div>
        </div>
      </div>
    </zz-dialog>
  </div>
</template>
<script>
import Vue from 'vue'
import { mapGetters } from 'vuex'
import { elevatorInfoMaintain, updateElevatorStatus, getGroupRefer, getTowerDevice, getCodeList } from '../../../service/api.js'

export default {
  name: 'towerInfo',
  computed: {
      ...mapGetters({
        currentUser: 'currentUser'
      })
    },
    data () {
      return {
        periodList: {},
        biaoduanList: {},
        producerList: {},
        modelNameList: {},
        numList: {},
        radioList: [
          {id: 1, check: false, name: '是'},
          {id: 2, check: false, name: '否'}
        ],
        detailInfo: {},
        periodName: '', // 期次
        biaoduanName: '',
        towerObject: {
          deviceType: 2,  // 设备类型  1.升降机，2塔机
          id: '',					 //设备id   --》有则对设备修改，无则新建设备
          code: '',			    // 自编号  			(必填)
          deviceName: '',		     //设备标识			(必填)
          referId	:'',		     //绑定监控设备		(必填)
          referName: '',
          sourceDid:'',
          isSelf:'',			     //是否自有设备		(必填) 1是 0否
          companyCode:'',        //  企业统一设备编码	
          producerId :'',         // 生产厂家id			
          producerName  :'',     //  生产厂家名称		
          modelId  :'',          //  规格型号id			
          modelName :'',          // 规格型号名称		
          outNumber :'',          // 出厂编号			
          outDate	:'',		     //出厂日期				（String类型）
          initialNumber:'',      //  初始登记号			
          maxHigh:'',            //  最大安装高度		
          setupCapability :'',    // 设备安装性能表		
          projectId :'',         //  项目ID				
          insertUser:'',	       //  插入人				
          stageId :'',           //  分期id				
          sectionId :'',         //  标段id				
          companyId :'',         //  企业id				
          departmentId:'',       //  部门id	
          status: 1,			
          mid:'' ,                 // 人员id
          useYear: '' , //使用年限
          enterTime: ''  //进厂日期
        },
        towerStatus: 1,  //1 在用 2 退场 3删除
        foctoryList: [],
        standardList: [],
        showDialog: false,
        dialogTitle: '塔吊监控设备',
        groupRefer: [], // 监控列表
        codeName: '',
        panoramaFile: [],
        panoramaFileList: [],
        panoramaFileUuid: [],
        picList: [],
        momentPicArray : '',
        changePic: 0 //默认图片没有修改为0
      }
    },
    props: {
      towerItem: {
        type: Object,
        default: {}
      },
      projectId: ''
    },
    mounted () {
      if (this.towerItem && this.towerItem.deviceId) {
        // 修改
        this.getInfo()
      } else {
        // 新增
      }
      this.getCode ()
      this.getPeriods()
      this.getFoctoryList()
      this.getStandardList()
      this.getGroup()
    },
    methods: {
      // 获取自编号列表
      getCode () {
        getCodeList({
          coId: this.currentUser.coId,
          mid: this.currentUser.mid,
          pjId: this.projectId,
          deviceType: 2,  //1 升降机 2 塔吊
          pjId: this.currentUser.pjId
        }).then( res => {
          this.numList = {}
          for (let i = 0; i < res.data.length; i++) {
            this.numList[i] = res.data[i]
          }
        }).catch( err => {
          console.log(err)
        })
      },
      // 获取项目所有的期次
      getPeriods () {
        const data = {
            'query.type': 'stage',
            'query.projectId': this.projectId
        }
        this.$axios({
          method: 'post',
          data: Vue.prototype.$qs.stringify(data),
          url: `${this.$site.projectServer}/front/person/findSectionList.htm`
        }).then(res => {
          //console.log(res)
          this.periodList = {}
          for (let item of res.data.list) {
            this.periodList[item.stageId] =  item.stageName
          }
        })
      },
      setPeriod (item) {
        // 设置期次
        this.getBidaoduanlist(item.key)
        this.towerObject.stageId = item.key
        this.towerObject.stageName = this.periodList[item.key]
      },
      // 获取项目标段信息
      getBidaoduanlist (stageId) {
        const data = {
          'query.projectId': this.projectId,
          'query.type': 'section',
          'query.stageId': stageId
        }
        this.$axios({
          method: 'post',
          data: Vue.prototype.$qs.stringify(data),
          url: `${this.$site.projectServer}/front/person/findSectionList.htm`
        }).then(res => {
          this.biaoduanList = {}
          for (let item of res.data.list) {
            this.biaoduanList[item.section_id] =  item.section_name
          }
        })
      },
      setBiaoduan (item) {
        // 设置标段
        this.towerObject.sectionId = item.key
        this.towerObject.sectionName = this.biaoduanList[item.key]
      },
      // 获取设备档案
      getInfo () {
        getTowerDevice({
          coId: this.currentUser.coId,
          mid: this.currentUser.mid,
          pjId: this.projectId,
          deviceType: 2,
          deviceId: this.towerItem.deviceId  // 设备id
        }).then( res => {
          this.towerObject = res.data
          if(res.data.fileList && res.data.fileList.length > 0) {
            this.$fileUpload.setFiles(res.data.fileList)
          }
          this.picList = res.data.fileList
          if (this.towerObject.isSelf === 1) {
            this.radioList[0].check = true
            this.radioList[1].check = false
          } else {
            this.towerObject.companyCode = ''
            this.radioList[0].check = false
            this.radioList[1].check = true
          }
          if (!this.towerObject.referId) {
            this.towerObject.referId = ''
          }
          if (this.towerObject.outDate) {
            this.towerObject.outDate = this.$moment(Number(this.towerObject.outDate)).format('YYYY-MM-DD')
          }
          if (this.towerObject.enterTime) {
            this.towerObject.enterTime = this.$moment(Number(this.towerObject.enterTime)).format('YYYY-MM-DD')
          }
        }).catch( err => {
          console.log(err)
        })
      },
      // 更新设备状态，如离场
      updateElevator () {
        updateElevatorStatus({
          coId: this.currentUser.coId,
          mid: this.currentUser.mid,
          pjId: this.projectId,
          deviceType: 2,
          deviceId: this.towerItem.deviceId,
          status: this.towerStatus // 1在用 2退场 3删除
        }).then( res => {
           this.$emit('close')
           this.$emit('refresh')
        }).catch( err => {
          console.log(err)
        })
      },
      // 获取监控列表
      getGroup () {
        getGroupRefer({
          coId: this.currentUser.coId,
          mid: this.currentUser.mid,
          pjId: this.projectId,
          deviceType: 2
        }).then( res => {
          this.groupRefer = res.data
          for (let i = 0; i<this.groupRefer.length; i++) {
            this.groupRefer[i].status = false
            if (this.towerObject.referId && this.groupRefer[i].referId === this.towerObject.referId) {
              this.towerObject.deviceName = this.groupRefer[i].deviceName
              this.towerObject.deviceSn = this.groupRefer[i].deviceSn
              this.towerObject.referName = this.groupRefer[i].deviceName
            }
          }
        }).catch( err => {
          console.log(err)
        })
      },
      // 选择监控设备
      chooseDevice (item, index) {
        for (let i = 0; i < this.groupRefer.length; i++ ) {
          this.groupRefer[i].status = false
          document.getElementsByClassName('groupReferGroup')[i].className = 'groupReferGroup'
        }
        this.groupRefer[index].status = true
        document.getElementsByClassName('groupReferGroup')[index].className = 'groupReferGroup choosed'
      },
      handleRadio (value) {
        // 自有设备选择触发事件
        if (value === 1) {
          this.radioList[0].check = true
          this.radioList[1].check = false
          this.towerObject.isSelf = 1
        } else {
          this.radioList[1].check = true
          this.radioList[0].check = false
          this.towerObject.isSelf = 0
          this.towerObject.companyCode = ''
        }
      },
      close () {
        this.towerObject = {
          deviceType: 2,  // 设备类型  1.升降机，2塔机
          id: '',					 //设备id   --》有则对设备修改，无则新建设备
          code: '',			    // 自编号  			(必填)
          deviceName: '',		     //设备标识			(必填)
          referId	:'',		     //绑定监控设备		(必填)
          isSelf:'',			     //是否自有设备		(必填) 1是 2否
          sourceDid: '',
          companyCode:'',        //  企业统一设备编码	
          producerId :'',         // 生产厂家id			
          producerName  :'',     //  生产厂家名称		
          modelId  :'',          //  规格型号id			
          modelName :'',          // 规格型号名称		
          outNumber :'',          // 出厂编号			
          outDate	:'',		     //出厂日期				（String类型）
          initialNumber:'',      //  初始登记号			
          maxHigh:'',            //  最大安装高度		
          setupCapability :'',    // 设备安装性能表		
          projectId :'',         //  项目ID				
          insertUser:'',	       //  插入人				
          stageId :'',           //  分期id				
          sectionId :'',         //  标段id				
          companyId :'',         //  企业id				
          departmentId:'',       //  部门id		
          status: 1,		
          mid:'' ,                 // 人员id
          useYear: '', //使用年限
          enterTime: ''   // 进厂日期
        },
        this.changePic = 0
        this.$emit('close')
      },
      // 拍照上传
      updatePanoramaFileHandel (files) {
        // this.panoramaFileList = files
        this.picList = files
        this.panoramaUploadList = files.map((file) => {
          return file.fileUuid
        })
        this.panoramaFileUuid = this.panoramaUploadList
        this.getMomentPicArray()
      },
      getMomentPicArray () {
        this.changePic = 1
        this.momentPicArray = this.panoramaFileUuid.join(',')
        return
      },
      save () {
        // 保存设备档案 新增/修改
        //console.log(this.panoramaFileUuid)
        let d = ''
        if (this.towerObject.outDate) {
          d = new Date(this.towerObject.outDate)
        }
        if (this.panoramaFileUuid.length > 9) {
          this.$message.error('最多只能上传个文件')
          return
        }
        if(!this.towerObject.stageId || !this.towerObject.sectionId || !this.towerObject.stageName || !this.towerObject.sectionName) {
          this.$message.error('请选择所属标段')
          return
        } else if (!this.towerObject.code) {
          this.$message.error('请选择自编号')
          return
        } else if (!this.towerObject.deviceName) {
          this.$message.error('请填写设备标识')
          return
        } else {}
        let deviceDto = {
          coId: this.currentUser.coId,
          pjId: this.projectId,
          mid:this.currentUser.mid,                 // 人员id          
          deviceType: 2,  // 设备类型  1.升降机，2塔机
          id: this.towerItem.deviceId || '',					 //设备id   --》有则对设备修改，无则新建设备
          code: this.towerObject.code,			    // 自编号  			(必填)
          deviceName: this.towerObject.deviceName,		     //设备标识			(必填)
          referId	:this.towerObject.referId,		     //绑定监控设备		(必填)
          isSelf:this.towerObject.isSelf,			     //是否自有设备		(必填) 1是 0否
          sourceDid: this.towerObject.sourceDid,
          companyCode:this.towerObject.companyCode,        //  企业统一设备编码	
          producerId :this.towerObject.producerId,         // 生产厂家id			
          producerName  :this.towerObject.producerName,     //  生产厂家名称		
          modelId : this.towerObject.modelId,          //  规格型号id			
          modelName : this.towerObject.modelName,          // 规格型号名称		
          outNumber :this.towerObject.outNumber,          // 出厂编号			
          outDate	: d ? d.getTime() : '',		     //出厂日期				（String类型）
          initialNumber:this.towerObject.initialNumber,      //  初始登记号			
          maxHigh:this.towerObject.maxHigh,            //  最大安装高度		
          setupCapability : this.changePic === 1 ? this.momentPicArray : this.towerObject.setupCapability,    // 设备安装性能表			
          insertUser:this.towerObject.insertUser,	       //  插入人				
          stageId :this.towerObject.stageId,           //  分期id				
          sectionId :this.towerObject.sectionId,         //  标段id	
          stageName: this.towerObject.stageName,
          sectionName: this.towerObject.sectionName,			
          companyId :this.towerObject.companyId,         //  企业id		
          status: this.towerObject.status,
          departmentId:this.towerObject.departmentId,       //  部门id				
          useYear: this.towerObject.useYear,  //使用年限
          enterTime: this.towerObject.enterTime || this.$moment().format('YY-MM-DD')   // 进厂日期
        }
        let data = {
          'deviceDto': deviceDto,   
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.videoServer}/api/device/elevatorInfoMaintain`,
          data: data,
          dataType:"json",
          contentType: "application/json;charset=utf-8"
        }).then(res => {
          this.$emit('close')
          this.$emit('refresh')
        }).catch( err => {
          this.$message.error('设置失败')
        })
      },
      getFoctoryList () {
        // 工厂列表
        const data = {
        }
        this.$axios({
          method: 'post',
          data: Vue.prototype.$qs.stringify(data),
          // url: `http://zz.bgy.t.pinming.org/machineWeb/findProducer.htm`
          url: `${this.$site.zhgdServer}/machineWeb/findProducer.htm`
        }).then(res => {
          this.producerList = {}
          for (let item of res.data.list) {
            this.producerList[item.producerId] = item.name
          }
        })
      },
      // 设置生产厂家
      setProdecer (item) {
        this.towerObject.producerId = item.key
        this.towerObject.producerName = this.producerList[item.key]
      },
      getStandardList () {
        // 规格列表
        const data = {
        }
        this.$axios({
          method: 'post',
          data: Vue.prototype.$qs.stringify(data),
          // url: `http://zz.bgy.t.pinming.org/machineWeb/findMachineModel.htm`
          url: `${this.$site.zhgdServer}/machineWeb/findMachineModel.htm`
        }).then(res => {
          this.modelNameList = {}
          for (let item of res.data.list) {
            this.modelNameList[item.modelId] = item.model
          }
        })
      },
      setModel (item) {
        // 设置规格
        this.towerObject.modelId = item.key
        this.towerObject.modelName = this.modelNameList[item.key]
      },
      handleChange (state) {
        this.towerObject.outDate = state
      },
      handleChange2 (state) {
        // this.date = state
        this.towerObject.enterTime = state
      },
      num (item) {
        // 设置自编号
        this.towerObject.code = item.value
      },
      // 绑定监控设备
      setReferId () {
        // 显示弹窗
        this.showDialog = true
      },
      // 离场
      goout() {
        this.towerStatus = 2
        this.$MessageBox({
          title: '离场确认',
          showClose: true,
          message: '确认该设备已离场？离场设备，系统将不再统计其运行记录',
          type: 'info',
          closeValue: '在想想',
          confirmValue: '确认',
          confirmHanler: () => {
            this.updateElevator()
          },
          cancel: () => {
            console.log('取消')
          }
        })
      },
      // 进场
      regoin () {
        this.towerStatus = 1
        this.$MessageBox({
          title: '提示',
          showClose: true,
          message: '确定设置该设备为在场状态',
          type: 'info',
          closeValue: '在想想',
          confirmValue: '确认',
          confirmHanler: () => {
            this.updateElevator()
          },
          cancel: () => {
            console.log('取消')
          }
        })
      },
      // 删除
      delTower () {
        this.towerStatus = 3
        this.$MessageBox({
          title: '删除确认',
          showClose: true,
          message: '删除设备后，该设备的记录将删除。确认删除该设备？',
          type: 'info',
          closeValue: '在想想',
          confirmValue: '确认',
          confirmHanler: () => {
            this.updateElevator()
          },
          cancel: () => {
            console.log('取消')
          }
        })
      },
      closeDialog () {
        this.showDialog = false
      },
    confirm () {
      for (let i = 0; i<this.groupRefer.length; i++) {
        if (this.groupRefer[i].status){
          this.towerObject.referId = this.groupRefer[i].referId
          this.towerObject.sourceDid = this.groupRefer[i].sourceDid
          this.towerObject.referName = this.groupRefer[i].deviceName
          this.towerObject.deviceSn = this.groupRefer[i].deviceSn
        }
      }
      this.showDialog = false
    }  
    }
}
</script>

<style lang="scss" scoped>
  .tit {
    font-weight: bold;
    border-left: 2px solid $color;
    padding-left: 10px;
  }
  table {
    margin: 15px 0;
    border: 1px solid #e6e6e6;
    width: 100%;
    border-spacing: 0;
    border-collapse: collapse;
    table-layout:fixed;
    .producer-input,.modelName-input {
      position: absolute;
      top: 10px;
      height: 18px;
      z-index: 1;
      width: 130px;
    }
    .producer-input {
      width: 350px;
    }
    tr {
      height: 38px;
    }
    .takePic {
      height: 80px;
      th {
        text-align: center;
        padding: 0;
        line-height: 24px;
      }
      td {
        .icon-plus {
          width: 30px;
          height: 30px;
        }
      }
    }
    th,td {
      border: 1px solid #e6e6e6;
      padding-left: 16px;
    }
    th {
      background: #eff0f2;
      color: #989898;
      text-align: left;
      font-weight: 500;
    }
    td {
      position: relative;
      input {
        border: 0;
        width: 90%;
      }
      .chooseBtn {
        color: $color;
        position: absolute;
        right: 10px;
        top: 11px;
        font-size: 14px;
        border:0;
      }
    }
  }
  .pic-contain {
    height: 190px;
    border: 0;
    overflow-y: scroll;
    overflow-x: hidden;
    &::-webkit-scrollbar {
      display: none;
     }
  }
  .footer-button {
    position: absolute;
    bottom: 0;
    width: 938px;
    margin-left: -20px;
    margin-bottom: -20px;
    background: #f0f4f5;
    height: 66px;
    text-align: right;
    button {
      margin-top: 15px;
      background: #fff;
      &:hover {
        background: $color;
      }
    }
  }
  .groupReferGroup {
    height: 50px;
    margin-bottom: 5px;
    position: relative;
    .left-side{
      float: left;
      padding-right: 20px;
      i {
        color: #fff;
        font-size: 36px;
        display: block;
        text-align: center;
        background: $color;
      }
    }
    .right-side {
      >div {
        padding-bottom: 10px;
      }
    }
    .icon-success {
      position: absolute;
      right: 0;
      top: 0;
      color: $color;
      display: none;
    }
  }
  .choosed {
    .icon-success {
      display: block;
    }
  }
</style>

